import React, { useRef, useEffect } from "react";
import { findIndex } from "lodash";

function DragLayout({ data, children, className, style, onChange }) {
  const startDom = useRef(null);
  const endDom = useRef(null);
  const refs = useRef([]);

  const onDragEnd = (e) => {
    console.log("onDragEnd", e);
    var from = startDom.current.dataset.id;
    var to = endDom.current.dataset.id;
    let fromIndex = -1;
    let toIndex = -1;
    // const { height } = startDom.current.getBoundingClientRect();

    // startDom.current.style.display = "none";

    data.forEach((item, index) => {
      if (item.id === from) {
        fromIndex = index;
      }
      if (item.id === to) {
        toIndex = index;
      }
      if (fromIndex != -1 && toIndex != -1) {
        return;
      }
    });

    data.forEach((item, sindex) => {
      refs.current[sindex].style = `transform:translateY(${0}px); `;
    });

    data.splice(toIndex, 0, data.splice(fromIndex, 1)[0]);
    onChange && onChange(data);
  };

  const onDragStart = (e) => {
    console.log("onDragStart", e);
    startDom.current = e.target;
    e.dataTransfer.setData("Text", e.target.id);
  };

  const onDrag = (e) => {
    console.log("onDrag", e);
    if (e.target.dataset.id === startDom.current.dataset.id) {
      startDom.current.style.opacity = 0;
    }
  };

  const onDragOver = (e) => {
    e.preventDefault();
    console.log("onDrag", e);
    if (!e.target?.dataset?.id) {
      return;
    }

    if (startDom.current) {
      const onIndex = data.findIndex(
        (item) => item.id === e.target?.dataset?.id
      );
      const currentIndex = data.findIndex(
        (item) => item.id === startDom.current?.dataset?.id
      );

      const { height } = startDom.current.getBoundingClientRect();
      let translateY = onIndex >= currentIndex ? -height : height;

      if (onIndex > currentIndex) {
        refs.current[
          onIndex
        ].style = `transform:translateY(${translateY}px);transition: transform 0.2s; `;
      } else if (onIndex < currentIndex) {
        refs.current[
          onIndex
        ].style = `transform:translateY(${translateY}px);transition: transform 0.2s; `;
      }
    }

    endDom.current = e.target;
  };
  const renderItem = () => {
    return children.map((item, index) => {
      return (
        <div
          key={data?.[index]?.["id"]}
          data-id={data?.[index]?.["id"]}
          draggable={"true"}
          onDragEnd={onDragEnd}
          onDrag={onDrag}
          onDragStart={onDragStart}
          ref={(ref) => (refs.current[index] = ref)}
        >
          {item}
        </div>
      );
    });
  };
  return (
    <div
      onDragOver={onDragOver}
      className={className || ""}
      style={style || {}}
    >
      {renderItem()}
    </div>
  );
}
export default DragLayout;
